import { routerRedux } from 'dva/router';
import { message } from 'antd';
import * as api from '../utils/api';

const MESSAGESUCCESS = message.success
const MESSAGEERROR = message.error
export default {

    namespace: 'userinfo',

    state: {
        userinfo: {},
        menuList:[],
        routerItems:[],
        pathNameList:[]
    },
    effects: {
        *postLogin({ payload }, { call, put }) {
            const res = yield call(api.postLogin, payload);
            if (res.code === 0) {
                MESSAGESUCCESS('登录成功(*^ω^*)')
                yield put({
                    type: 'updateUserInfo',
                    action: res.data
                })
                const menu = yield call(api.getMenuTable, {
                    data: { t: new Date().getTime() },
                    method: 'GET'
                });
                if(menu.code === 0) {
                    yield put({
                        type: 'updateMenuList',
                        action: menu.data
                    })
                } else {
                    MESSAGEERROR('(︶︿︶)' + res.msg)
                }
                yield put(routerRedux.replace('/'))
            } else {
                MESSAGEERROR('(︶︿︶)' + res.msg)
            }
        },
        *signOut({ payload }, { call, put }) {
            if(payload === 'signOut'){
                yield put({
                    type: 'updateUserInfo',
                    action: payload
                })
                Object.keys(sessionStorage).forEach(key=>{
                    console.log(key)
                    sessionStorage.removeItem(key)
                })  
                yield put(routerRedux.replace('/login'))
                MESSAGESUCCESS('退出成功(*^ω^*)')
            }else{
                yield put(routerRedux.replace('/personal'))
            }
        }
    },
    reducers: {
        'updateUserInfo'(state, { action: userinfo }) {
            let newState = Object.assign({}, state)
            newState.userinfo = userinfo
            return newState
        },
        'updateMenuList'(state, { action: data }) {
            let newState = Object.assign({}, state)
            newState.menuList = data
            return newState
        },
        'updateRouterPath'(state, { action: data }) {
            let newState = Object.assign({}, state)
            newState.routerItems = data.newRouters
            newState.pathNameList = data.pathList
            return newState
        }
    },
};
